import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Button,
  Modal,
  DatePicker,
  Space,
  Form,
  Input,
  Select,
  TreeSelect,
} from "antd";
import { text_check, format_time, post_axios } from "../../utils";
import dayjs from "dayjs";

export default function EditUser(props) {
  const { t } = useTranslation();
  const {
    edit_user_title,
    edit_user_show,
    search_data,
    edit_type,
    kind_list,
    com_list,
    role_list,
    mch_list,
    circuit_list,
    setEdit_user_show,
    local_company_object,
    clicked_user_obj,
    user_com_list,
    user_kind_list,
  } = props;

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  const [role_selected_grade, setRole_selected_grade] = useState();
  const { Option } = Select;
  const { RangePicker } = DatePicker;
  const [form] = Form.useForm();
  const role_selected_func = (value) => {
    let role_grade = role_list.filter((item) => item.role_id == value)[0]
      .role_grade;
    form.setFieldsValue({
      array_com_id: [],
      array_kind_id: [],
    });
    setRole_selected_grade(role_grade);
  };

  const identify_status_list = [
    {
      key: "enable",
      msg_en: "Yes",
      msg_cn: "是",
    },
    {
      key: "disable",
      msg_en: "No",
      msg_cn: "否",
    },
  ];
  const onFinish = (values) => {
    console.log(values);
    edit_user_confirm(values);
  };
  const onReset = () => {
    form.resetFields();
  };
  const edit_user_confirm = async (value) => {
    let {
      username,
      name,
      last_name,
      role_id,
      array_com_id,
      array_kind_id,
      tel,
      email,
      enable_verify,
      data_time,
    } = value;
    let upMsg = {
      username,
      name,
      role_id,
      array_kind_id: JSON.parse(JSON.stringify(array_kind_id)),
      tel,
      email,
      enable_verify,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    if (data_time && data_time.length === 2) {
      upMsg["datatime1"] = format_time(data_time[0], "time_date") + " 00:00:00";
      upMsg["datatime2"] = format_time(data_time[1], "time_date") + " 23:59:59";
    }
    if (
      role_selected_grade === 62 ||
      role_selected_grade === 63 ||
      role_selected_grade === 64
    ) {
      let com_arr = JSON.parse(JSON.stringify(array_com_id));
      upMsg["array_com_id"] = com_arr.map((item) => item.value);
    } else {
      upMsg["array_com_id"] = JSON.parse(JSON.stringify(array_com_id));
    }
    if (session_company === "mg") {
      upMsg["last_name"] = last_name;
    }
    let action = edit_type == "add" ? "m_add" : "m_modify";
    let res = await post_axios("user_manager", action, upMsg);
    if (!res) return;
    search_data();
    setEdit_user_show(false);
  };
  useEffect(() => {
    if (!edit_user_show) return;
    if (edit_type === "add") {
      onReset();
    } else {
      let {
        username,
        name,
        tel,
        email,
        last_name,
        role_id,
        role_grade,
        datatime1,
        datatime2,
        enable_verify,
      } = clicked_user_obj;
      setRole_selected_grade(role_grade);
      setTimeout(() => {
        form.setFieldsValue({
          username: username,
          name: name,
          tel: tel ? tel : "",
          email: email ? email : "",
          last_name: last_name ? last_name : "",
          role_id: role_id,
          enable_verify: enable_verify ? enable_verify : "enable",
          data_time: datatime1 && datatime2 ? [dayjs(datatime1),dayjs(datatime2)] : [],
        });
        switch (role_grade) {
          case 62:
          case 63:
          case 64:
            // 获取用户选择的组织
            form.setFieldsValue({
              array_com_id: user_com_list.map((item) => {
                return {
                  value: item.com_id,
                  label: item.com,
                };
              }),
            });
            break;
          case 70:
            // 获取用户选择的商户
            form.setFieldsValue({
              array_com_id: user_com_list.map((item) => item.mch_id),
            });
            break;
          case 80:
            // 获取用户选择的线路
            form.setFieldsValue({
              array_com_id: user_com_list.map((item) => item.circuit__id),
            });
            break;
          default:
            break;
        }
        form.setFieldsValue({
          array_kind_id: user_kind_list.map((item) => item.kind),
        });
      });
    }
  }, [edit_user_show]);
  return (
    <>
      <Modal
        forceRender
        title={edit_user_title}
        open={edit_user_show}
        classNames={{
          body: "edit_dialog_body edit_user_ruleForm",
          wrapper: "edit_user_style",
        }}
        onCancel={() => setEdit_user_show(false)}
        maskClosable={false}
        destroyOnClose={true}
        footer={null}
      >
        <Form
          form={form}
          variant="filled"
          className="edit_user_ruleForm"
          labelCol={{ span: 8, offset: 0 }}
          onFinish={onFinish}
          initialValues={{ enable_verify: "enable" }}
        >
          <div className="form_classify_box">
            <div className="form_classify_title">
              {t("system_manager.essential_information")}
            </div>
            <div className="form_ipt_box">
              <Form.Item
                label={t("system_manager.login_account")}
                name="username"
                rules={[
                  {
                    required: true,
                    pattern: new RegExp("^[a-zA-Z0-9_]+$", "g"),
                    message: t("system_manager.no_chinese"),
                  },
                ]}
              >
                <Input disabled={edit_type == "change"} />
              </Form.Item>
            </div>
            <div className="form_ipt_box">
              <Form.Item
                label={t("system_manager.username")}
                name="name"
                rules={[
                  {
                    required: true,
                    message: t("system_manager.enter_name"),
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </div>
            {session_company === "mg" ? (
              <div className="form_ipt_box">
                <Form.Item
                  label={t("system_manager.last_name")}
                  name="last_name"
                  rules={[
                    {
                      required: true,
                      message: t("system_manager.enter_lastname"),
                    },
                  ]}
                >
                  <Input />
                </Form.Item>{" "}
              </div>
            ) : (
              ""
            )}
          </div>
          <div className="form_classify_box">
            <div className="form_classify_title">
              {t("system_manager.power_grade")}
            </div>
            {session_company !== "mg" ? (
              <div className="form_ipt_box">
                <Form.Item
                  label="手机号"
                  name="tel"
                  rules={[
                    {
                      required: true,
                      pattern: new RegExp(/^1[3456789]\d{9}$/),
                      message: "请输入正确格式的手机号!",
                    },
                  ]}
                >
                  <Input />
                </Form.Item>{" "}
              </div>
            ) : (
              ""
            )}

            <div className="form_ipt_box">
              <Form.Item
                label="Email"
                name="email"
                rules={[
                  {
                    required: true,
                    message: t("system_manager.enter_email"),
                  },
                ]}
              >
                <Input />
              </Form.Item>
            </div>
            <div className="form_ipt_box">
              <Form.Item
                name="enable_verify"
                label={t("system_manager.enable_verify")}
              >
                <Select placeholder=" ">
                  {identify_status_list.map((item) => {
                    return (
                      <Option value={item.key} key={item.key}>
                        {text_check(item)}
                      </Option>
                    );
                  })}
                </Select>
              </Form.Item>
            </div>

            <div className="form_ipt_box">
              <Form.Item
                name="role_id"
                label={t("system_manager.role_grade")}
                rules={[
                  {
                    required: true,
                    message: t("system_manager.choose_role"),
                  },
                ]}
              >
                <Select
                  placeholder=" "
                  options={role_list}
                  fieldNames={{
                    label: "role_name",
                    value: "role_id",
                  }}
                  onChange={role_selected_func}
                />
              </Form.Item>
            </div>
            {role_selected_grade > 61 ? (
              <div className="form_ipt_box">
                <Form.Item
                  name="array_kind_id"
                  label={t("system_manager.kind")}
                >
                  <Select
                    placeholder=" "
                    mode="multiple"
                    options={kind_list}
                    fieldNames={{
                      label: "name",
                      value: "kind",
                    }}
                  />
                </Form.Item>
              </div>
            ) : (
              ""
            )}

            {role_selected_grade == 62 ||
            role_selected_grade == 63 ||
            role_selected_grade == 64 ? (
              <div className="form_ipt_box">
                <Form.Item
                  name="array_com_id"
                  label={t("system_manager.organization")}
                  rules={[
                    {
                      required: true,
                    },
                  ]}
                >
                  <TreeSelect
                    treeData={com_list}
                    multiple
                    treeCheckStrictly={true}
                    fieldNames={{
                      label: "com",
                      value: "com_id",
                      children: "children",
                    }}
                    placeholder=" "
                    treeCheckable={true}
                  />
                </Form.Item>
              </div>
            ) : (
              ""
            )}

            {role_selected_grade === 70 ? (
              <div className="form_ipt_box">
                <Form.Item
                  name="array_com_id"
                  label={t("system_manager.merchant")}
                  rules={[
                    {
                      required: true,
                    },
                  ]}
                >
                  <Select
                    placeholder=" "
                    mode="multiple"
                    options={mch_list}
                    fieldNames={{
                      label: "mch",
                      value: "mch_id",
                    }}
                  />
                </Form.Item>
              </div>
            ) : (
              ""
            )}

            {role_selected_grade === 80 ? (
              <div className="form_ipt_box">
                <Form.Item
                  name="array_com_id"
                  label={t("system_manager.line")}
                  rules={[
                    {
                      type: "array",
                      required: true,
                      message: t("system_manager.choose_com"),
                    },
                  ]}
                >
                  <Select
                    placeholder=" "
                    mode="multiple"
                    options={circuit_list}
                    fieldNames={{
                      label: "circuit",
                      value: "circuit_id",
                    }}
                  />
                </Form.Item>
              </div>
            ) : (
              ""
            )}
          </div>
          <div className="form_classify_box">
            <div className="form_classify_title">
              {t("system_manager.data_time_section")}
            </div>

            <div className="form_ipt_box">
              <Form.Item name="data_time" label={t("system_manager.time")}>
                <RangePicker />
              </Form.Item>
            </div>
          </div>
          <div className="form_ipt_btn">
            <Form.Item
              wrapperCol={{
                offset: 8,
                span: 16,
              }}
            >
              <Space>
                <Button
                  htmlType="button"
                  onClick={() => setEdit_user_show(false)}
                >
                  {t("common.cancel")}
                </Button>
                <Button type="primary" htmlType="submit">
                  {t("common.confirm")}
                </Button>
              </Space>
            </Form.Item>
          </div>
        </Form>
      </Modal>
    </>
  );
}
